package com.losdun.points.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.losdun.common.utils.bean.BeanUtils;
import com.losdun.common.utils.uuid.IdUtils;
import com.losdun.points.domain.PointsGoods;
import com.losdun.points.domain.PointsOrder;
import com.losdun.points.enums.PointsOrderStatusEnum;
import com.losdun.points.enums.PointsSourceTypeEnum;
import com.losdun.points.enums.PointsTypeEnum;
import com.losdun.points.mapper.PointsOrderMapper;
import com.losdun.points.service.PointsGoodsService;
import com.losdun.points.service.PointsOrderService;
import com.losdun.points.service.PointsRecordService;
import com.losdun.points.service.UserPointsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 积分订单表service实现类
 *
 * @author swordye
 * @date 2025-05-19
 */
@Slf4j
@Service
public class PointsOrderServiceImpl extends ServiceImpl<PointsOrderMapper, PointsOrder> implements PointsOrderService {
    @Autowired
    private PointsGoodsService pointsGoodsService;
    @Autowired
    private UserPointsService userPointsService;
    @Autowired
    private PointsRecordService pointsRecordService;

    @Override
    public List<PointsOrder> queryList(PointsOrder order) {

        List<PointsOrder> list = baseMapper.selectList(new QueryWrapper<>(order).orderByDesc("create_time"));
        if(CollectionUtils.isNotEmpty(list)){
           list.forEach(item -> {
                item.setGoods(pointsGoodsService.getById(item.getGoodsId()));
            });
        }
        return list;
    }

    @Override
    public void insertOrder(PointsOrder order) {
        pointsGoodsService.checkGoodsStock(order.getGoodsId(), order.getGoodsNum());
        boolean isPointOk = userPointsService.checkPoints(order.getUserId(), order.getTotalPoints());
        if(!isPointOk){
            throw new RuntimeException("兑换所需积分不足！");
        }
        order.setOrderNo(IdUtils.generateOrderNo("P"));
        order.setStatus(PointsOrderStatusEnum.wait_send.getCode());
        baseMapper.insert(order);
        //扣除积分
        pointsRecordService.updateUserPointsRecord(order.getUserId(), PointsSourceTypeEnum.STORE.getCode(), PointsTypeEnum.SUB.getCode(),order.getTotalPoints(),"积分商城兑换商品;订单号："+order.getOrderNo());
    }

    @Override
    public void cancelOrder(Long orderId, Long userId) {
        PointsOrder order = baseMapper.selectById(orderId);
        if(!order.getUserId().equals(userId)){
            throw new RuntimeException("订单取消失败,订单不存在!");
        }
        if(!PointsOrderStatusEnum.wait_send.getCode().equals(order.getStatus())){
            throw new RuntimeException("订单取消失败,订单非待发货状态!");
        }
        order.setStatus(PointsOrderStatusEnum.cancel.getCode());
        order.setCancelTime(LocalDateTime.now());
        baseMapper.updateById(order);

        //返还积分
        pointsRecordService.updateUserPointsRecord(order.getUserId(), PointsSourceTypeEnum.STORE.getCode(), PointsTypeEnum.ADD.getCode(),order.getTotalPoints(),"积分商城取消订单返还积分;订单号："+order.getOrderNo());

    }

    @Override
    public void updateOrder(PointsOrder order) throws Exception{
        PointsOrder entity = baseMapper.selectById(order.getId());
        if(entity==null){
            throw new RuntimeException("订单更新失败,订单不存在!");
        }
        if(!entity.getUserId().equals(order.getUserId())){
            throw new RuntimeException("订单更新失败,订单不存在!");
        }
        BeanUtils.copyProperties(entity,order);
        baseMapper.updateById(entity);
    }

    @Override
    public void orderDelivery(Long orderId, PointsOrder order) {
        PointsOrder entity = baseMapper.selectById(orderId);
        if(entity==null){
            throw new RuntimeException("订单发货失败,订单不存在!");
        }
        if(!entity.getUserId().equals(order.getUserId())){
            throw new RuntimeException("订单发货失败,订单不存在!");
        }
        if(!PointsOrderStatusEnum.wait_send.getCode().equals(entity.getStatus())){
            throw new RuntimeException("订单发货失败,订单非待发货状态!");
        }
        entity.setStatus(PointsOrderStatusEnum.sended.getCode());
        entity.setDeliveryTime(LocalDateTime.now());
        entity.setDeliveryCode(order.getDeliveryCode());
        entity.setDeliveryName(order.getDeliveryName());
        baseMapper.updateById(entity);
    }

    @Override
    public void orderConfirmReceived(Long orderId,Long userId) {
        PointsOrder entity = baseMapper.selectById(orderId);
        if(entity==null){
            throw new RuntimeException("订单收货失败,订单不存在!");
        }
        if(!entity.getUserId().equals(userId)){
            throw new RuntimeException("订单收货失败,订单不存在!");
        }
        if(!PointsOrderStatusEnum.sended.getCode().equals(entity.getStatus())){
            throw new RuntimeException("订单收货失败,订单非发货状态!");
        }
        entity.setStatus(PointsOrderStatusEnum.received.getCode());
        entity.setReceivedTime(LocalDateTime.now());
        baseMapper.updateById(entity);
    }

    @Override
    public PointsOrder getDetail(Long orderId, Long userId) {
        PointsOrder entity = baseMapper.selectById(orderId);
        if(entity==null || !entity.getUserId().equals(userId)){
            throw new RuntimeException("订单收货失败,订单不存在!");
        }
        PointsGoods goods = pointsGoodsService.getById(entity.getGoodsId());
        entity.setGoods(goods);
        return entity;
    }
}
